package com.lx.sync.config.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lx.sync.common.util.CacheUtil;
import com.lx.sync.config.mapper.SyncConfigMapper;
import com.lx.sync.config.model.SyncConfig;
import com.lx.sync.config.service.SyncConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 同步配置服务实现类
 */
@Slf4j
@Service("syncConfigService")
public class SyncConfigServiceImpl extends ServiceImpl<SyncConfigMapper, SyncConfig> implements SyncConfigService {

    private static final String CACHE_KEY_PREFIX = "sync:config:";
    private static final long CACHE_EXPIRE_DAYS = 30;

    @Autowired
    private SyncConfigMapper syncConfigMapper;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSyncConfig(@Valid SyncConfig config) {
        try {
            // 检查索引名称是否已存在
            if (syncConfigMapper.selectCount(new LambdaQueryWrapper<SyncConfig>()
                    .eq(SyncConfig::getIdxName, config.getIdxName())) > 0) {
                log.warn("配置已存在，请使用更新接口: {}", config.getIdxName());
                return false;
            }

            // 保存到数据库
            int result = syncConfigMapper.insert(config);
            if (result > 0) {
                // 更新缓存
                updateCache(config);
                log.info("保存同步配置成功: {}", config.getIdxName());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("保存同步配置失败: {}", config.getIdxName(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSyncConfig(@Valid SyncConfig config) {
        try {
            // 检查配置是否存在
            if (syncConfigMapper.selectCount(new LambdaQueryWrapper<SyncConfig>()
                    .eq(SyncConfig::getIdxName, config.getIdxName())) == 0) {
                log.warn("配置不存在，请先创建: {}", config.getIdxName());
                return false;
            }

            // 更新数据库
            int result = syncConfigMapper.updateById(config);
            if (result > 0) {
                // 更新缓存
                updateCache(config);
                log.info("更新同步配置成功: {}", config.getIdxName());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新同步配置失败: {}", config.getIdxName(), e);
            throw e;
        }
    }

    @Override
    public SyncConfig getSyncConfig(String idxName) {
        try {
            // 先从缓存获取
            String cacheKey = CACHE_KEY_PREFIX + idxName;
            SyncConfig config = null;
//            if (config != null) {
//                return config;
//            }

            // 缓存未命中，从数据库获取
            config = syncConfigMapper.selectOne(
                new LambdaQueryWrapper<SyncConfig>()
                    .eq(SyncConfig::getIdxName, idxName)
            );

            if (config != null) {
                // 更新缓存
                updateCache(config);
            }
            return config;
        } catch (Exception e) {
            log.error("获取同步配置失败: {}", idxName, e);
            return null;
        }
    }

    @Override
    public List<SyncConfig> getAllSyncConfigs() {
        try {
            return syncConfigMapper.selectList(null);
        } catch (Exception e) {
            log.error("获取所有同步配置失败", e);
            return Lists.newArrayList();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSyncConfig(String idxName) {
        try {
            // 从数据库删除
            int result = syncConfigMapper.delete(new LambdaQueryWrapper<SyncConfig>()
                    .eq(SyncConfig::getIdxName, idxName));
            if (result > 0) {
                // 删除缓存
                String cacheKey = CACHE_KEY_PREFIX + idxName;
                cacheUtil.del(cacheKey);
                log.info("删除同步配置成功: {}", idxName);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除同步配置失败: {}", idxName, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleSyncConfig(String idxName, boolean enabled) {
        try {
            SyncConfig config = getSyncConfig(idxName);
            if (config == null) {
                log.warn("配置不存在: {}", idxName);
                return false;
            }

            config.setEnabled(enabled);
            return updateSyncConfig(config);
        } catch (Exception e) {
            log.error("{}同步配置失败: {}", enabled ? "启用" : "禁用", idxName, e);
            throw e;
        }
    }

    /**
     * 更新缓存
     */
    private void updateCache(SyncConfig config) {
        try {
            String cacheKey = CACHE_KEY_PREFIX + config.getIdxName();
            cacheUtil.set(cacheKey, config, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
        } catch (Exception e) {
            log.error("更新缓存失败: {}", config.getIdxName(), e);
        }
    }
}
